package com.study.thread;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;

/**
 * @description 生产者
 * @author hw
 * @date 2022/1/2 18:12:15
 */
@Data
public class ProducerThread implements Runnable{

    Logger logger = LoggerFactory.getLogger(ProducerThread.class);

    //包
    private Queue<String> bags;

    //限定包的数量
    private int maxSize;

    public ProducerThread(Queue<String> bags, int maxSize) {
        this.bags = bags;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        int i = 0;
        //循环
        while (true){
            i++;
            //锁
            synchronized (bags){
                //包满了, 循环等待
                while (bags.size() == maxSize){
                    try {
                        logger.info("bags已满, 等待消费...");
                        //等待
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //睡一秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String bag = "包" + i;
                //生产包
                bags.add(bag);
                //打印
                logger.info("生产了一个包: " + bag);
                //唤醒消费者
                bags.notifyAll();
            }
        }
    }
}
